import pyvisa
import time
import serial
from instruments_dst import GHS_64
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 创建资源管理器
rm = pyvisa.ResourceManager()

# 连接到HMP4040设备
instrument = rm.open_resource('GPIB0::5::INSTR')

# 设置SCPI命令的发送和接收超时时间
instrument.timeout = 10000  # 10000毫秒

# 函数：发送I2C配置文件
def send_i2c_config_file(session, filename):
    """
    发送I2C配置文件到设备
    Args:
        session: 串口通信对象
        filename: 配置文件的名称
    """
    try:
        # 打开配置文件
        with open(filename, 'rb') as file:
            # 读取文件内容
            data = file.read()
            # 发送I2C起始信号
            session.write(b"I2C_START")
            # 等待设备响应
            time.sleep(0.1)
            session.write(data)
            # 发送I2C停止信号
            session.write(b"I2C_STOP")
            time.sleep(0.1)
            # 读取设备响应
            ret = session.read(session.in_waiting)
            # 打印调试信息
            logging.info(ret)
    except Exception as e:
        # 打印异常信息
        logging.error(f"发送I2C配置文件失败: {e}")

# 函数：检测完成标志
def check_completion(session):
    """
    检测完成标志
    Args:
        session: 串口通信对象
    Returns:
        bool: 如果检测到完成标志返回True，否则返回False
    """
    try:
        # 发送检测完成标志的命令
        session.write(b"CHECK_COMPLETION")
        # 等待设备响应
        time.sleep(0.1)
        ret = session.read(session.in_waiting)
        # 如果设备返回特定的完成标志，则认为操作完成
        if b"COMPLETION_OK" in ret:
            logging.info("完成标志检测成功")
            return True
        else:
            logging.info("完成标志检测失败")
            return False
    except Exception as e:
        # 打印异常信息
        logging.error(f"检测完成标志失败: {e}")
        return False

# 函数：设置输出电压
def set_voltage(channel, voltage):
    command = f"SOURce:VOLTage:LEVel:IMMediate {voltage}"
    instrument.write(f"INSTrument:SELect {channel};")
    instrument.write(command)

# 步骤1：设置通道1和通道2的输出电压
set_voltage('OUTPut1', 9)
set_voltage('OUTPut2', 3.17)

# 步骤2：通过I2C工具给寄存器发送配置文件
ghs_64 = GHS_64('COM_PORT')  # 替换'COM_PORT'为实际的串口端口
send_i2c_config_file(ghs_64.session, 'config_file.txt')

# 步骤3：检测是否有完成标志
if check_completion(ghs_64.session):
    logging.info("完成标志检测成功")
else:
    logging.info("完成标志检测失败")

# 重复步骤2和步骤3，步骤4和步骤5，步骤6和步骤7
for voltage in [3.3, 3.45]:
    set_voltage('OUTPut1', 9)
    set_voltage('OUTPut2', voltage)
    send_i2c_config_file(ghs_64.session, 'config_file.txt')
    if check_completion(ghs_64.session):
        logging.info("完成标志检测成功")
    else:
        logging.info("完成标志检测失败")

# 关闭设备连接
instrument.close()
rm.close()
ghs_64.session.close()  # 关闭GHS_64类的串口连接